package com.mms.service;

import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSessionManager;

import com.mms.dao.CustomerMapper;
import com.mms.dao.FollowUpMapper;
import com.mms.entity.Customer;
import com.mms.entity.CustomerState;
import com.mms.entity.FollowUp;
import com.mms.util.MyBatisUtilsPlus;

public class FollowUpServiceImpl implements FollowUpService {

	private SqlSessionManager sessionManager = MyBatisUtilsPlus.getSqlSessionManager();
	private FollowUpMapper followUpMapper = MyBatisUtilsPlus.getMapper(FollowUpMapper.class);
	private CustomerMapper customerMapper = MyBatisUtilsPlus.getMapper(CustomerMapper.class);

	@Override
	public void save(FollowUp newFollowUp) {
		// ：：开启事务
		this.sessionManager.startManagedSession();
		// 操作1：插入跟进记录到followup表
		this.followUpMapper.insert(newFollowUp);
		// 操作2：更新customer表中对应记录的last_follow_up_date、last_follow_up_note，如果经过本次跟进该客户成交了，还需更新state、deal_date
		int custId = newFollowUp.getCustId();
		Date lastFollowUpDate = newFollowUp.getFollowUpDate();
		String lastFollowUpNote = newFollowUp.getFollowUpNote();
		CustomerState state = newFollowUp.getCustomerState();
		// 先查到对应客户的原始数据
		Customer customer = this.customerMapper.selectByPrimaryKey(custId);
		// 无论如何，现在有一次新的跟进，必须涉及到更新对应客户的state、last_follow_up_date、last_follow_up_note
		customer.setState(state);
		customer.setLastFollowUpDate(lastFollowUpDate);
		customer.setLastFollowUpNote(lastFollowUpNote);
		// 如果经过本次跟进，该客户成交了，还得更新这个客户的成交日期deal_date
		if (newFollowUp.getCustomerState() == CustomerState.DEALED) {
			customer.setDealDate(newFollowUp.getFollowUpDate());
		}
		// 更新到数据库
		this.customerMapper.updateByPrimaryKey(customer);
		// ：：提交事务
		this.sessionManager.commit();
		this.sessionManager.close();
	}

	@Override
	public List<FollowUp> listFollowUpHistory(int custId) {
		return this.followUpMapper.selectByCustId(custId);
	}

}
